const rest = require('restler');
const sd = require("silly-datetime");
const router = require("koa-router")();
const DB = require("../module/db");
const os = require('os')
const env = process.env

router.post("/", async (ctx) => {

    console.log("env.client_id:",env.client_id)
    console.log("env.redirect_uri:",env.redirect_uri)
    console.log("env.client_secret:",env.client_secret)
    console.log("env.cg_uri:",env.cg_uri)

    console.log('cgyunLogin.code:', ctx.request.body.code);

    let localUrl = getIPAdress()

    let client_id = 'shannewsightcgverify'
    let redirect_uri = 'http://39.97.101.97:8090/login';
    let client_secret = 'secret';
    let cg_uri = 'http://cgyun.cn';
    if (env.client_id !== undefined ){
        client_id =env.client_id
        console.log('1111111111')
    }
    if(env.redirect_uri !== undefined){
        redirect_uri = env.redirect_uri
    }
    if(env.client_secret !== undefined){
        client_secret = env.client_secret
    }
    if(env.cg_uri !== undefined){
        cg_uri = env.cg_uri
    }


    if (ctx.request.body.code !== '') {
        let userData = {}
        const insert = new Promise((resolve) => {
            //第一次请求
            let url1 = cg_uri +'/auth/v1/oauth/token'
            rest.post(url1, {
                data: {
                    code: ctx.request.body.code,
                    "grant_type": "authorization_code",
                    "redirect_uri": redirect_uri,
                    "client_id": client_id,
                    "client_secret": client_secret,
                    "scope": "read"
                }
            }).on('complete', function (result) {
                console.log('result1:', result)
                if (result.access_token !== undefined) {
                    userData['access_token'] = result.access_token
                    //第二次请求
                    let url2 = cg_uri + '/auth/v1/users/get?'
                    rest.post(url2, {
                        data: {
                            "access_token": userData['access_token']
                        }
                    }).on('complete', function (result) {
                        console.log("result2:", result)
                        userData['team'] = 'cgyun'

                        userData['alias'] = result.data.name
                        userData['username'] = result.data.username
                        userData['password'] = ''

                        //第三次请求
                        let url3 = cg_uri + '/cg/v1/team/authenticate'
                        rest.post(url3, {
                            headers: {
                                "Authorization": "Bearer " + userData['access_token']
                            },
                            data: {
                                "client_id": client_id,
                                "resource_group": 'CGTEAM',
                            }
                        }).on('complete', function (result) {
                            console.log("result3:", result)
                            // userData['team'] = result.team
                            userData['teamName'] = result.teamName
                            userData['teamAlias'] = result.teamAlias
                            userData['role'] = result.data
                            userData['enable'] = 'true'
                            userData['createDate'] = new Date()
                            userData['photoFileID'] = ''
                            userData['__v'] = '0'
                            // console.log('userData:', userData)
                            insertUser(userData).then((data) => {
                                userData['_id'] = data
                                resolve(userData)
                            })
                        })
                    });
                }
            })
        })

        await insert.then(
            data => ctx.body = {
                type: 1,
                info: data
            },
            err => console.log(err)
        );
    } else {
        ctx.body = {
            type: 0,
        }
    }


});

async function insertUser(userData) {
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let dataFindResult = await DB.find('user', {"username": userData.username});
    if (dataFindResult.toString().length === 0) {
        let dataInsertResult = await DB.insert('user', userData);
        try {
            if (dataInsertResult.result.ok) {
                console.log(time + "：添加用户成功" + userData.username);
            } else {
                console.log(time + "：插入失败");
            }
            // console.log(dataInsertResult.ops[0]._id)

            let list = {
                "name": "新的项目",
                "userId": dataInsertResult.ops[0]._id.toString(),
                "reviews": [],
                "introduction": "欢迎来到新项目...",
                "collections": [],
            }
            let addProjectResult = await DB.insert('project', list);
            try {
                if (addProjectResult.result.ok) {
                    console.log(time + "：添加项目成功" + list.name);
                } else {
                    console.log(time + "：添加项目失败")
                }
            } catch (e1) {
                console.log(time + "：" + e1);
            }
        } catch (e2) {
            console.log(time + "：" + e2);
        }
        return dataInsertResult.ops[0]._id.toString()
    } else {
        // if (dataFindResult[0].code === '')
        //     await DB.update("user", {"username": userData.username}, userData)
        await DB.update("user", {"username": userData.username}, userData)
        console.log(time + ' : 用户' + userData.username + '登录成功')
        return dataFindResult[0]._id
    }
}

///获取本机ip///
function getIPAdress() {
    let interfaces = os.networkInterfaces();
    for (let devName in interfaces) {
        let iface = interfaces[devName];
        for (let i = 0; i < iface.length; i++) {
            let alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

global.insertUser = insertUser;
module.exports = router.routes();
